package drds.global_transaction.api.rpc.rpc_client;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcClientHandler extends ChannelDuplexHandler
{

	public RpcClientHandler()
	{

	}

	//

	@Override
	public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception
	{
		super.channelInactive(channelHandlerContext);
	}

	@Override
	public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception
	{
		super.channelActive(channelHandlerContext);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void channelRead(final ChannelHandlerContext channelHandlerContext, final Object message) throws Exception
	{
		final String request = (String) message;
		log.info("client:" + message);
		try
		{
			channelHandlerContext.writeAndFlush(request, channelHandlerContext.voidPromise());
		} catch (Exception e)
		{
			log.error("when try flush error", e);
		}
	}

	@Override
	public void write(ChannelHandlerContext channelHandlerContext, Object message, ChannelPromise channelPromise) throws Exception
	{
		channelHandlerContext.write(message, channelPromise);
	}

	@Override
	public void flush(ChannelHandlerContext channelHandlerContext) throws Exception
	{
		channelHandlerContext.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause) throws Exception
	{
		channelHandlerContext.close();
	}

}
